<template>
  <view>
    <!-- 头部 -->
    <yHeader :current="current" @Tabs="handleTabs"></yHeader>
    <!-- 内容 -->
    <view class="bg-grey py-4">
      <view class="__inner">
        <!-- 订单详情 -->
        <view class="p-2 px-4 bg-white">
          <el-button @click="Black" type="primary">返回上一页</el-button>
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column
              align="center"
              type="index"
              label="序号"
              width="55"
            ></el-table-column>
            <el-table-column
              prop="Article_Name"
              label="商品名称"
              align="center"
            ></el-table-column>
            <el-table-column align="center" prop="Quantity" label="交易量">
              <template v-slot="{ row }">
                {{ row.Quantity }}{{ row.Unit }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="Amount" label="交易金额">
              <template v-slot="{ row }"
                >￥
                {{ (Number(row.Amount) * Number(row.Quantity)).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Collection_Amount"
              label="已付金额"
            >
              <template v-slot="{ row }">
                ￥{{ Number(row.Collection_Amount).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="未付金额">
              <template v-slot="{ row }">
                ￥
                {{
                  (
                    Number(row.Amount) * Number(row.Quantity) -
                    Number(row.Collection_Amount)
                  ).toFixed(2)
                }}
              </template>
            </el-table-column>
            <el-table-column
              v-if="lock == 0"
              prop="Seller_Contact"
              label="卖方姓名"
              align="center"
            ></el-table-column>
            <el-table-column
              v-else
              prop="Contacts"
              label="对方企业"
              align="center"
            ></el-table-column>
            <el-table-column
              v-if="lock == 0"
              align="center"
              prop="Seller_Contact_Phone"
              label="联系人"
            ></el-table-column>
            <el-table-column
              v-else
              align="center"
              prop="Contacts_Phone"
              label="对方手机号"
            ></el-table-column>
            <!-- <el-table-column align="center" label="交易状态">
							<template v-slot="{row}">
								<text v-if="row.Row_Status=='0'&&row.Seller_Status=='0'">待对方审核</text>
								<text v-if="row.Row_Status=='1'&&row.Seller_Status=='0'">待双方确认合同</text>
								<text v-if="row.Row_Status=='4'&&row.Seller_Status=='0'">待我方确认合同</text>
								<text v-if="row.Row_Status=='1'&&row.Seller_Status=='4'">待对方确认合同</text>
								<text v-if="row.Row_Status=='4'&&row.Seller_Status=='4'&&row.Trading_Name=='全款'">待我方付全款</text>
								<view v-if="row.Trading_Name!='全款'" class="">
									<text v-if="row.Row_Status=='4'&&row.Trading_Detail_SerialNumber.includes('T01000000000001_0')&&row.Seller_Status=='4'">待我方付首款</text>
									<text v-if="row.Row_Status=='5'&&row.Trading_Detail_SerialNumber.includes('T01000000000001_0')&&row.Seller_Status=='4'">待对方付首款</text>
									<text v-if="row.Row_Status=='5'&&row.Trading_Detail_SerialNumber.includes('T01000000000002_0')&&row.Trading_Detail_SerialNumber.includes('T01000000000001_1')">待我方付下一笔款</text>
									<text v-if="row.Row_Status=='4'&&row.Trading_Detail_SerialNumber.includes('T01000000000003_0')&&row.Trading_Detail_SerialNumber.includes('T01000000000002_1')">待对方付下一笔款</text>
									<text v-if="row.Row_Status=='6'&&row.Trading_Detail_SerialNumber.includes('T01000000000004_0')&&row.Trading_Detail_SerialNumber.includes('T01000000000003_1')">待对方付尾款</text>
									<text v-if="row.Row_Status=='4'&&row.Seller_Status=='4'&&row.Trading_Detail_SerialNumber.includes('T01000000000001_1')">待我方发货</text>
								</view>
								<text v-if="row.Row_Status=='6'&&row.Seller_Status=='4'&&Number(row.Amount)*Number(row.Quantity)==Number(row.Collection_Amount)">交易结束</text>
							</template>
						</el-table-column> -->
          </el-table>
          <el-table
            v-if="tableData1.length != 0"
            class="mt-2"
            :data="tableData1"
            border
            style="width: 100%"
          >
            <el-table-column
              prop="Transport_Type"
              align="center"
              label="运输方式"
            >
            </el-table-column>
            <el-table-column align="center" label="物流信息编号">
              <template v-slot="{ row }">
                <el-tooltip
                  effect="dark"
                  :content="row.Group_Seek_Logistics_SerialNumber"
                  placement="top"
                >
                  <view class="text-ellipsis w-100">
                    <text>{{ row.Group_Seek_Logistics_SerialNumber }}</text>
                  </view>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Article_Name"
              label="物流信息"
            >
              <template v-slot="{ row }">
                <el-tooltip
                  effect="dark"
                  :content="row.Transport_Explain"
                  placement="top"
                >
                  <view class="text-ellipsis w-100">
                    <text>{{ row.Transport_Explain }}</text>
                  </view>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </view>
        <view class="p-4 bg-white mb-4">
          <view
            class="my-4 w-100 border border-grey"
            style="box-sizing: border-box"
          >
            <view class="flex bg-lightbrown" style="height: 80rpx">
              <view
                class="flex flex-shrink justify-center align-center"
                style="width: 30%; height: 100%"
              >
                <text class="font">{{ pagename }}</text>
              </view>
              <view
                class="flex justify-center align-center"
                style="width: 20%; height: 100%"
              >
                <text class="font">{{ pageed }}</text>
              </view>
              <view
                class="flex justify-center align-center"
                style="width: 20%; height: 100%"
              >
                <text class="font">{{ pageprice }}</text>
              </view>
              <view
                class="flex justify-center align-center"
                style="width: 20%; height: 100%"
              >
                <text class="font">最晚付款时间</text>
              </view>
              <view
                class="flex justify-center align-center"
                style="width: 20%; height: 100%"
              >
                <text class="font">操作</text>
              </view>
            </view>
            <view
              class="flex align-center py-4"
              v-for="(item, i) in Data"
              :key="i"
            >
              <view
                class="flex justify-center flex-shrink align-center"
                style="width: 30%; height: 150rpx"
              >
                <text class="font">{{ item.Trading_Detail_Name }}</text>
              </view>
              <view
                class="flex justify-center align-center"
                style="width: 20%; height: 100%"
              >
                <text class="font">{{ item.Trading_Amount }}%</text>
              </view>
              <view
                class="flex justify-center align-center"
                style="width: 20%; height: 100%"
              >
                <text class="font" :class="'text-' + ThemeColors"
                  >￥{{ item.Amount }}</text
                >
              </view>
              <view
                class="flex justify-center align-center"
                style="width: 20%; height: 100%"
              >
                <text class="font">{{ item.Trading_Date }}天后</text>
              </view>
              <view
                v-if="lock == 0"
                class="flex justify-center align-center"
                style="width: 20%; height: 100%"
              >
                <el-button
                  v-if="item.Row_Status == '0'"
                  @click="ChoosePayway(item)"
                  type="primary"
                  >选择付款方式</el-button
                >
                <el-button v-else type="danger">付款完成</el-button>
              </view>
              <view
                v-else
                class="flex justify-center align-center"
                style="width: 20%; height: 100%"
              >
                <el-tag v-if="item.Row_Status == '0'" type="danger"
                  >对方未完成付款</el-tag
                >
                <el-tag v-else type="success">付款完成</el-tag>
              </view>
            </view>
          </view>
        </view>
        <view
          class="bg-lightbrown border px-4"
          :class="'border-' + ThemeColors"
          style="box-sizing: border-box"
        >
          <view
            class="flex align-center justify-end w-100"
            style="height: 80rpx"
          >
            <text class="font-md"
              >货品总金额：￥{{
                Number(tableData[0].Amount) * Number(tableData[0].Quantity)
              }}</text
            >
          </view>
          <view
            class="flex align-center justify-end w-100"
            style="height: 80rpx"
          >
            <text class="font-md">运费金额：￥0.00</text>
          </view>
          <view class="flex align-end justify-end w-100" style="height: 120rpx">
            <text class="font-lg"
              >订单总价：<text class="h2" :class="'text-' + ThemeColors"
                >￥{{
                  Number(tableData[0].Amount) * Number(tableData[0].Quantity)
                }}</text
              >元</text
            >
          </view>
        </view>
      </view>
    </view>
    <!-- 底部 -->
    <yFooter></yFooter>
    <!-- 选择支付方式 -->
    <el-dialog title="选择支付方式" :visible.sync="dislogChoosePay">
      <el-radio-group
        @change="ChangeradioValue"
        class="w-100"
        v-model="radioValue"
      >
        <view class="flex w-100" style="justify-content: space-evenly">
          <view
            v-for="(item, i) in PayWay"
            :key="i"
            class="flex flex-column justify-center align-center"
          >
            <el-radio :label="item.id">{{ item.label }}</el-radio>
            <image
              style="width: 150rpx; height: 150rpx"
              :src="item.src"
              mode=""
            >
            </image>
          </view>
        </view>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dislogChoosePay = false">取 消</el-button>
        <el-button type="primary" @click="SurePayWay()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 付款二维码 -->
    <el-dialog title="支付二维码" :visible.sync="dislogPayCode">
      <view class="flex justify-center">
        <uqrcode
          ref="uqrcode"
          canvas-id="qrcode"
          :value="codeurl"
          :options="{ margin: 10 }"
        >
        </uqrcode>
      </view>
      <view class="flex justify-center">
        <el-button type="danger" @click="back()">返回上一页</el-button>
        <el-button :loading="loading" type="primary" @click="CompletePayfor()"
          >支付完成后点击此处</el-button
        >
      </view>
    </el-dialog>
    <!-- 电汇上传 -->
    <el-dialog title="电汇" :visible.sync="dislogPayTicket">
      <view class="flex justify-center w-100">
        <!-- <uni-file-picker :disabled="imgdisabled" v-model="img" @select="UpdateImg" limit="1"
					:title="title"></uni-file-picker> -->
        <view>
          <view class="preview" v-show="imageUrl2">
            <el-image
              class="el-upload-list__item-thumbnail"
              style="width: 148px; height: 148px"
              :src="imageUrl2"
              fit="contain"
            ></el-image>
            <span class="el-upload-list__item-actions">
              <!-- <span @click="handlePictureCardPreview()"
                ><i class="el-icon-zoom-in"></i
              ></span>
              <span @click="handleRemove('front')"
                ><i class="el-icon-delete"></i
              ></span> -->
              <!-- :disabled="imgdisabled" -->
            </span>
          </view>
          <el-upload
            v-show="!imageUrl2"
            class="upload-demo"
            :show-file-list="false"
            list-type="picture-card"
            action=""
            accept="image/*"
            :before-upload="UpdateImg"
          >
            <i slot="default" class="el-icon-plus"></i>
            <view class="el-upload__tip" slot="tip"> 请上传电汇单 </view>
          </el-upload>
        </view>
      </view>
      <view class="flex justify-center">
        <el-button type="danger" @click="back()">返回上一页</el-button>
        <el-button
          :loading="loading"
          :disabled="Picture_URL == ''"
          type="primary"
          @click="ElectronicRemittance()"
          >确认上传</el-button
        >
      </view>
    </el-dialog>
  </view>
</template>

<script>
import times from "@/static/js/utils.js";
const app = getApp();
import yHeader from "@/components/yHeader.vue";
import yFooter from "@/components/yFooter.vue";
import { Message } from "element-ui";
import {
  TransactionPaystagesID,
  GroupWeChatNativeAction,
  GroupSeekElectronicRemittance,
  ElectronicPIC,
  getGroupSeekProcureIDAction,
  SeekTransactionPaystagesID,
} from "@/api/group.js";
import {
  getAddAction,
  getSubtableInquiryOriginal,
  GoodsInquiryKeyOriginal,
  getInquiryIDOriginal,
  getEditAction,
  parseBankReceiptVoucherAction,
} from "@/api/global.js";
import compressor from "@/static/js/compressor.js";
export default {
  components: {
    yHeader,
    yFooter,
  },
  data() {
    return {
      title: "加载中...请稍后",
      loading: false,
      img: [],
      Data: [],
      formData: {},
      radioValue: 1,
      imgdisabled: true,
      Group_Seek_Paystages_SerialNumber: "",
      Group_Seek_Transaction_SerialNumber: "",
      Enterprise_Info_SerialNumber: "",
      Amount: "",
      Picture_URL: "",
      Collection_SerialNumber: "",
      dislogChoosePay: false,
      dislogPayCode: false,
      dislogPayTicket: false,
      codeurl: "",
      Domain_IMG: app.globalData.Domain_IMG,
      ThemeColors: app.globalData.ThemeColors,
      PaystagesData: {},
      current: -1,
      tableData: [],
      tableData1: [],
      pagename: "付款阶段",
      pageed: "付款额度",
      pageprice: "付款金额",
      PayWay: [
        {
          id: 1,
          label: "微信支付",
          src: "../../static/icon/WXlogo.png",
        },
        {
          id: 2,
          label: "支付宝支付",
          src: "../../static/icon/zfb.png",
        },
        {
          id: 3,
          label: "电汇",
          src: "../../static/icon/dzhz.png",
        },
      ],
      lock: "",
      Time: null,
      imageUrl2: "",
    };
  },
  onLoad(options) {
    // if (options.type == 'supply') {
    // 	this.current == 2
    // } else if (options.type == 'purchase') {
    // 	this.current == 3
    // }
    this.lock = options.a;
    console.log(this.lock);
    if (this.lock == 1) {
      this.pagename = "对方付款阶段";
      this.pageed = "对方付款额度";
      this.pageprice = "对方付款金额";
    } else {
      this.pagename = "付款阶段";
      this.pageed = "付款额度";
      this.pageprice = "付款金额";
    }
    this.Group_Seek_Transaction_SerialNumber =
      options.Group_Seek_Transaction_SerialNumber;
    let data = {
      Group_Seek_Transaction_SerialNumber:
        options.Group_Seek_Transaction_SerialNumber,
    };
    this.tableData.push(JSON.parse(uni.getStorageSync("detail")));
    console.log(this.tableData);
    this.getDetail(data);
    this.getLogistics();
  },
  methods: {
    handleTabs(url) {
      uni.navigateTo({
        url,
      });
    },
    Black() {
      uni.navigateBack();
    },
    async getLogistics() {
      const res = await getInquiryIDOriginal({
        data: {
          Data: "group_seek_transaction_logistics",
          Primary_Key_Name: "Group_Seek_Transaction_SerialNumber",
          Primary_Key: this.Group_Seek_Transaction_SerialNumber,
          isNullEnterprise: true,
        },
      });
      console.log(res);
      this.tableData1 = res;
    },
    async getDetail(data) {
      const res = await SeekTransactionPaystagesID({
        data,
      });
      if (res.redirect && res.redirect == "REDIRECT") {
        console.log(res.redirect);
      } else if (res.Status == "success") {
        console.log(res);
        this.Data = res.Data;
      }
    },
    ChoosePayway(item) {
      console.log(item);
      this.dislogChoosePay = true;
      this.Group_Seek_Paystages_SerialNumber =
        item.Group_Seek_Paystages_SerialNumber;
      this.Amount = item.Amount;
    },
    ChangeradioValue(e) {
      console.log(this.radioValue);
    },
    async CodeUrl(data) {
      this.dislogPayCode = true;
      const res = await GroupWeChatNativeAction({
        data,
      });
      if (res.redirect && res.redirect == "REDIRECT") {
        console.log(res.redirect);
      } else {
        console.log(res);
        if (res.code_url) {
          this.codeurl = res.code_url;
          this.Time = setInterval(() => {
            let Data = {
              Data: "collection",
              Primary_Key_Name: "Collection_SerialNumber",
              Primary_Key: res.Data,
              isNullEnterprise: true,
            };
            this.getPayNotice(Data);
          }, 1000);
          return;
        }
        if (res.Data) {
          this.Collection_SerialNumber = res.Data;
          this.title = "请上传一张电汇发票";
          this.imgdisabled = false;
        }
      }
    },
    async getPayNotice(data) {
      const res = await getInquiryIDOriginal({
        data,
      });
      console.log(res);
      if (res[0].Row_Status == "1") {
        clearInterval(this.Time);
        this.Time = null;
        Message({
          type: "success",
          message: "已付款",
        });
        this.CompletePayfor();
      }
    },
    SurePayWay() {
      if (this.radioValue == 1) {
        // 微信支付
        if (this.codeurl == "") {
          let data = {
            Data: this.Group_Seek_Paystages_SerialNumber,
            Order_Type: "4",
            Collection_Type: "微信支付",
          };
          this.CodeUrl(data);
        } else {
          this.dislogPayCode = true;
        }
      } else if (this.radioValue == 2) {
        //支付宝支付
      } else {
        //电汇支付
        let data = {
          Data: this.Group_Seek_Paystages_SerialNumber,
          Order_Type: "4",
          Collection_Type: "电子汇账",
        };
        this.dislogPayTicket = true;
        this.CodeUrl(data);
      }
      this.dislogChoosePay = false;
    },
    async ElectronicRemittance() {
      this.loading = true;
      let data = {
        Picture_URL: this.Picture_URL,
        Collection_SerialNumber: this.Collection_SerialNumber,
        Purchase_Amount: this.Amount,
      };
      const res = await GroupSeekElectronicRemittance({
        data,
      });
      if (res.redirect && res.redirect == "REDIRECT") {
        console.log(res.redirect);
      } else {
        console.log(res);
        this.loading = false;
        Message({
          message: "提交成功！",
          type: "success",
        });
        this.getDetail({
          Group_Seek_Transaction_SerialNumber:
            this.Group_Seek_Transaction_SerialNumber,
        });
        this.img = [];
        this.imgdisabled = true;
        this.dislogPayTicket = false;
        this.dislogPayCode = false;
        this.dislogChoosePay = false;
      }
    },
    async CompletePayfor() {
      this.loading = true;
      let obj = {
        // 采购信息表
        group_seek_transaction: {
          group_seek_transaction_paystages: {},
        },
      };
      const res = await getSubtableInquiryOriginal({
        data: {
          Primary_Key: this.Group_Seek_Transaction_SerialNumber,
          JSONObject: JSON.stringify(obj),
          token: uni.getStorageSync("loginInfo").token,
        },
      });
      if (res.redirect && res.redirect == "REDIRECT") {
        console.log(res.redirect);
      } else if (res.Status == "success") {
        console.log(res);
        this.formData = res.group_seek_transaction[0];
        this.formData.Row_Status = "7";
        let group_message_buyer = {
          Group_Message_SerialNumber: "",
          Group_Seek_Transaction_SerialNumber:
            this.formData.Group_Seek_Transaction_SerialNumber,
          Cause: "对方已付款",
          Submission_Time: times.nowtime(),
          Enterprise_Info_SerialNumber:
            this.formData.Enterprise_Info_SerialNumber,
          Seller_Type: "1",
        };
        let Data = {
          Data: JSON.stringify({
            group_message: [group_message_buyer],
          }),
          token: uni.getStorageSync("loginInfo").token,
        };
        this.getAdd(Data);
      }
    },
    async getAdd(data) {
      const res = await getAddAction({
        data,
      });
      this.loading = false;
      if (res.redirect && res.redirect == "REDIRECT") {
        console.log(res.redirect);
      } else if (res.Status == "success") {
        console.log(res);
        this.getDetail({
          Group_Seek_Transaction_SerialNumber:
            this.Group_Seek_Transaction_SerialNumber,
        });
        this.dislogPayTicket = false;
        this.dislogPayCode = false;
        this.dislogChoosePay = false;
      }
    },
    // UpdateImg(e) {
    //   console.log(e);
    //   let Picture_URL;
    //   图片转base64
    //     uni.request({
    //       url: e.tempFilePaths[0],
    //       method: "GET",
    //       responseType: "arraybuffer",
    //       success: (ress) => {
    //         Picture_URL = uni.arrayBufferToBase64(ress.data); //把arraybuffer转成base64
    //         let data = {
    //           Data: "data:image/jpeg;base64," + Picture_URL,
    //           DataLength: e.tempFiles[0].size,
    //           FileName: e.tempFiles[0].name,
    //         };
    //         this.CheckImg(data);
    //       },
    //       fail: (e) => {
    //         console.log("图片转换失败");
    //       },
    //     });
    // },

    UpdateImg(file) {
      let Picture_URL;
      if (file.size > 2000000) {
        Message({
          type: "error",
          message: "上传图片过大",
        });
        return;
      }
      if (file.size < 5000) {
        Message({
          type: "error",
          message: "上传图片过小",
        });
        return;
      }
      const _this = this;
      console.log("file", file);
      new compressor(file, {
        quality: 1,
        success(file) {
          const formData = new FormData();
          formData.append("file", file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            // _this.CheckImg(e.target.result, file.name);
            // _this.imageUrl = e.target.result;
            Picture_URL = e.target.result; //把arraybuffer转成base64
            let data = {
              Data: "data:image/jpeg;base64," + Picture_URL,
              DataLength: file.size,
              FileName: file.name,
            };
            _this.CheckImg(data);
          };
        },
        error(err) {
          console.log(err.message);
        },
      });
    },

    async CheckImg(data) {
      const res = await parseBankReceiptVoucherAction({
        data,
      });
      console.log(res);
      if (res.redirect && res.redirect == "REDIRECT") {
        console.log(res.redirect);
      } else if (res.Status == "success") {
        this.Picture_URL = res.Picture_Url;
      } else {
        Message({
          message: "不是一张有效的电汇凭证",
          type: "error",
        });
      }
    },

    back() {
      this.dislogPayTicket = false;
      this.dislogPayCode = false;
      this.dislogChoosePay = true;
    },
  },
};
</script>

<style>
.example-body {
  padding: 10px;
  padding-top: 0;
}

.custom-image-box {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
  color: #333;
}
</style>